﻿package _6_FileChooser;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.Box;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.filechooser.FileFilter;

/**
 * 2011-6-5 22:47:56
 * 
 * @author Administrator 演示文件选择框的过滤使用
 */
public class TJFileChooser {
    JFrame frame;
    Container contentPane;
    JList<String> list;
    JButton selectButton;

    public TJFileChooser() {
        frame = new JFrame("文件选择框测试");
        contentPane = frame.getContentPane();
        list = new JList<String>();
        list.setModel(new DefaultListModel<String>());
        list.setVisibleRowCount(10);
        contentPane.add(new JScrollPane(list), BorderLayout.CENTER);
        selectButton = new JButton("选择");
        selectButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser jfc = new JFileChooser(".");
                jfc.setApproveButtonText("确认");
                jfc.setDialogTitle("文件选择");
                jfc.addChoosableFileFilter(new FileFilter() {
                    public boolean accept(File f) {
                        if (f.isDirectory()) {
                            return true;
                        }
                        return f.getName().endsWith(".txt");
                    }

                    public String getDescription() {
                        return new String("文本文件(*.txt)");
                    }
                });
                jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
                jfc.setMultiSelectionEnabled(true);
                int result = jfc.showOpenDialog(frame);
                if (result == JFileChooser.APPROVE_OPTION) {
                    File f[] = jfc.getSelectedFiles();
                    DefaultListModel<String> model = (DefaultListModel<String>) list.getModel();
                    model.removeAllElements();
                    for (int i = 0; i < f.length; i++) {
                        model.addElement(f[i].getName());
                    }
                }
            }
        });
        Box box = Box.createHorizontalBox();
        box.add(Box.createHorizontalGlue());
        box.add(selectButton);
        box.add(Box.createHorizontalGlue());
        contentPane.add(box, BorderLayout.SOUTH);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String args[]) {
        new TJFileChooser();
    }
}
